//
//  TroubleReportController.swift
//  ShareCar
//
//  Created by 久众科技 on 2018/8/24.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import Foundation

class TroubleReportController: UITableViewController {
    
    @IBOutlet weak var reasonTextField: UITextView!
    @IBOutlet weak var carNumberTextField: UITextField!
    
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var imageCollectionView: UICollectionView!
    
    @IBOutlet weak var height: NSLayoutConstraint!

    @IBOutlet weak var tipLabel: UILabel!
    @IBOutlet weak var cityButton: UIButton!
    var data = [User.Reasons.Reason]()
    
    var addressArray : User.addressInfo?
    var selectedReason = [String]()
    var imagePaths = [String]()
    
    var images = [UIImage]() {
        
        didSet {
            imageCollectionView.reloadData()
        }
    }
    
    //选择上的图片数组
    var isEdit: Bool = false            //标记是否是编辑
    var index: Int = 9000               //标记当前点击的是第几个

    override func viewDidLoad() {
        super.viewDidLoad()
        images.append(UIImage(named: "GroupCarmre")!)
        
        User.declareReason(success: { [weak self] data in
            if let data = data, let self = self {
                self.data = data
                let beishu = data.count / 3 * 50
                self.height.constant = CGFloat(Double(beishu))
                self.collectionView.reloadData()
            }
        }) { message in
            XHProgressHUD.showError(message.msg)
        }
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        User.chooseAdresscity(success: { [weak self] data in
            if let temp = data {
                self?.addressArray = temp
            }
        }) { message in
            XHProgressHUD.showError(message.msg)
        }
    }
    
    //TODO: IBaction
    @IBAction func commit(_ sender: Any) {
        
        if selectedReason.count == 0 {
            XHProgressHUD.showError("请选择上报原因")
            return
        }
        
        guard let number = carNumberTextField.text, carNumberTextField.text?.count != 0 else {
            XHProgressHUD.showError("请输入正确的车牌号")
            return
        }
        
        let title = cityButton.title(for: .normal)
        let value = title! + number 
        
        let cityName = cityButton.title(for: .normal)
        if var name = cityName {
            name.append(carNumberTextField.text ?? "")
        }
        
        JZLoading.showLoadingWith(toView: self.view)
        User.commitReason(reasons: selectedReason, plateNumber: value, otherReason: reasonTextField.text,imagePath: imagePaths, success: { [weak self] in
            JZLoading.hideLoading()
            XHProgressHUD.showSuccess("上报成功")
            self?.navigationController?.popViewController(animated: true)
        }) { message in
            JZLoading.hideLoading()
            XHProgressHUD.showError(message.msg)
        }
    }
    
    @IBAction func chooseImage(_ sender: UIButton) {
        
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let  cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
            cameraPicker.allowsEditing = true
            cameraPicker.sourceType = .camera
            //在需要的地方present出来
            present(cameraPicker, animated: true, completion: nil)
        } else {
            showError("不支持拍照")
        }
    }
    
    @IBAction func chooseAddress(_ sender: UIButton) {
        let arrays =  addressArray?.list
        let picker = CustomPicker(frame: CGRect.zero, items: arrays!)
        picker.zdefaultSelected = { [weak self] onename in
            self?.cityButton.setTitle(onename, for: .normal)
        }
        let win: UIWindow = UIApplication.shared.windows.last!
        win.addSubview(picker)
        picker.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
    }
}


extension TroubleReportController: UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if collectionView == self.collectionView {
            return self.data.count
        } else {
            return self.images.count == 6 ? images.count - 1 : images.count
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        if collectionView == self.collectionView {
            
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
            
            if let cell = cell as? TroubleReasonCollectionCell {
                cell.layer.cornerRadius = 4
                cell.layer.masksToBounds = true
                cell.layer.borderWidth = 1
                
                cell.layer.borderColor = UIColor(hexString: "bebec8")?.cgColor
                cell.layer.backgroundColor = UIColor.white.cgColor
                let item = data[indexPath.row]
                cell.reasonLabel.text = item.reasonName
                
                cell.reasonLabel.textColor = UIColor(red: 10.0/255.0, green: 11.0/255.0, blue: 65.0/255.0, alpha: 1.0)
                cell.reasonLabel.backgroundColor = UIColor(red: 241.0/255.0, green: 244.0/255.0, blue: 246.0/255.0, alpha: 1.0)
                
                if selectedReason.contains(item.reasonName) {
                    cell.layer.borderColor = UIColor(red: 252.0/255.0, green: 166.0/255.0, blue: 72.0/255.0, alpha: 1.0).cgColor
                    cell.reasonLabel.textColor = UIColor.white
                    cell.reasonLabel.backgroundColor = UIColor(red: 252.0/255.0, green: 166.0/255.0, blue: 72.0/255.0, alpha: 1.0)
                    
                    cell.layer.backgroundColor = UIColor(valueRGB: 0xFCA648, alpha: 1.0).cgColor
                }
            }
            return cell
            
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath)
            
            if let cell = cell as? TrobleUploadImageCell{
                cell.imageView.image = images[indexPath.row]
            }
            
            return cell
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if  collectionView == self.collectionView {
            
            let item = data[indexPath.row]
            if selectedReason.contains(item.reasonName) {
                //如果包含
                let index = selectedReason.index(of: item.reasonName)
                if let ind = index {
                    selectedReason.remove(at: ind)
                }
            } else {
                selectedReason.append(item.reasonName)
            }
            
            collectionView.reloadData()
        } else {
            if images.count == 6 && indexPath.row == images.count - 1 {
                XHProgressHUD.showError("最多上传五张图片")
                return
            }
            //标记
            index = indexPath.row
            isEdit = (indexPath.row == images.count - 1) ? false : true
            
            if UIImagePickerController.isSourceTypeAvailable(.camera){
                let  cameraPicker = UIImagePickerController()
                cameraPicker.delegate = self
                cameraPicker.allowsEditing = true
                cameraPicker.sourceType = .camera
                
                present(cameraPicker, animated: true, completion: nil)
            } else {
                showError("不支持拍照")
            }
        }
    }
}

extension TroubleReportController: UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextViewDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        
        let image:UIImage = info[UIImagePickerControllerEditedImage] as! UIImage
        
        //上传图片
        User.uploadFile(image) { [weak self] path in
            if let self = self {
                self.images.insert(image, at: self.images.count - 1)
                self.imagePaths.append(path)
            }
        }
        
        dismiss(animated: true, completion: nil)
    }
    
    func textViewDidChange(_ textView: UITextView) {
        tipLabel.isHidden = reasonTextField.text.count != 0
    }
}
